package id.laskarmedia.opnvpn_flutter;

import android.os.RemoteException;

import id.laskarmedia.opnvpn_flutter.bean.ServerConfig;
import id.laskarmedia.opnvpn_flutter.util.CheckInternetConnection;
import id.laskarmedia.opnvpn_flutter.util.PermissionUtil;
import top.oneconnectapi.app.OpenVpnApi;
import top.oneconnectapi.app.core.OpenVPNService;
import top.oneconnectapi.app.core.OpenVPNThread;

public class OpenVPNEngineer {

    private boolean vpnStart;
    private final OpenVPNThread vpnThread = new OpenVPNThread();
    private final OpenVPNService vpnService = new OpenVPNService();
    private ServerConfig server;
    private final CheckInternetConnection connection = new CheckInternetConnection();

    public boolean stopVpn() {
        try {
            vpnThread.stop();
            status("connect");
            vpnStart = false;
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            vpnStart = false;
        }
        return false;
    }

    public void startVpn() {
        if(server == null){
            throw new RuntimeException("serverConfig is null");
        }
        if(ContextHelper.getContext() == null){
            throw new RuntimeException("required context!");
        }
        try {
            OpenVpnApi.startVpn(ContextHelper.getContext(), server.getOvpn(), server.getCountry(), server.getOvpnUserName(), server.getOvpnUserPassword());
            status("Connecting...");
            vpnStart = true;

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void prepareVpn() {
        if (!connection.netCheck()) {
            showToast("you have no internet connection !!");
            return;
        }
        if (vpnStart) {
            stopVpn();
            showToast("Disconnect Successfully");
            return;
        }
        PermissionUtil.requestVPNPermission();
    }



    public void status(String status) {
        if (status.equals("connect")) {
        } else if (status.equals("connecting")) {
        } else if (status.equals("connected")) {
        } else if (status.equals("tryDifferentServer")) {
        } else if (status.equals("loading")) {
        } else if (status.equals("invalidDevice")) {
//            binding.vpnBtn.setBackgroundResource(R.drawable.button_connected);
        } else if (status.equals("authenticationCheck")) {
//            binding.vpnBtn.setBackgroundResource(R.drawable.button_connecting);
        }
    }

    public void showToast(String msg){

    }

    public void setServerConfig(ServerConfig config) {
        this.server = config;
    }
}
